/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.controller.dictionary;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Strings;
import com.je.auth.check.annotation.AuthCheckPermission;
import com.je.common.base.DynaBean;
import com.je.common.base.constants.dd.DDType;
import com.je.common.base.mapper.query.Query;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.result.DirectJsonResult;
import com.je.common.base.service.MetaService;
import com.je.common.base.service.rpc.BeanService;
import com.je.common.base.util.ArrayUtils;
import com.je.common.base.util.JEUUID;
import com.je.common.base.util.SecurityUserHolder;
import com.je.common.base.util.StringUtil;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.cache.dd.DicCache;
import com.je.meta.cache.dd.DicInfoCache;
import com.je.meta.cache.dd.DicQuickCache;
import com.je.meta.model.dd.DictionaryItemVo;
import com.je.meta.rpc.dictionary.DictionaryRpcService;
import com.je.meta.service.common.MetaBeanService;
import com.je.meta.service.common.MetaDevelopLogService;
import com.je.meta.service.dictionary.MetaDictionaryExtService;
import com.je.meta.service.setting.MetaSystemSettingService;
import com.je.meta.util.BasicSqlFormatterUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/je/meta/dictionary")
public class DictionaryController extends AbstractPlatformController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private DictionaryRpcService dictionaryRpcService;
    @Autowired
    private MetaDictionaryExtService metaDictionaryExtService;
    @Autowired
    private MetaDevelopLogService metaDevelopLogService;
    @Autowired
    private MetaService metaService;
    @Autowired
    public MetaSystemSettingService systemSettingService;
    @Autowired
    private DicInfoCache dicInfoCache;
    @Autowired
    private DicCache dicCache;
    @Autowired
    private DicQuickCache dicQuickCache;
    @Autowired
    private MetaBeanService metaBeanService;

    @AuthCheckPermission(value = "pc-func-JE_CORE_DICTIONARY-show")
    @RequestMapping(value = "/load", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @Override
    public BaseRespResult load(BaseMethodArgument param, HttpServletRequest request) {
        Query query = param.buildQuery();
        commonService.buildProductQuery(query);
        param.setjQuery(JSON.toJSONString(query));
        return super.load(param, request);
    }

    /**
     * 初始化加载字典
     *
     * @return
     */
    @RequestMapping(value = "/initLoad", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult initLoad(HttpServletRequest request) {
        String queryColumns = getStringParameter(request, "queryColumns");
        if (Strings.isNullOrEmpty(queryColumns)) {
            queryColumns = "DICTIONARY_DDCODE,DICTIONARY_DDNAME,DICTIONARY_DDTYPE,DICTIONARY_DICTYPE,DICTIONARY_ITEMROOT_ID,JE_CORE_DICTIONARY_ID";
        }
        //构建排序条件
        List<Map<String, Object>> list = metaService.selectSql(ConditionsWrapper.builder().table("JE_CORE_DICTIONARY").selectColumns(queryColumns));
        //构建返回json对象åå
        return BaseRespResult.successResult(list);
    }

    /**
     * 添加字典。。 级联添加字典项
     */
    @AuthCheckPermission(value = "pc-func-JE_CORE_DICTIONARY-show")
    @RequestMapping(value = "/doSaveDic", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult doSaveDic(BaseMethodArgument param, HttpServletRequest request) {
        String strData = param.getStrData();
        String dicStr = getStringParameter(request, "dicStr");
        if (StringUtil.isEmpty(dicStr) || StringUtil.isEmpty(strData)) {
            return BaseRespResult.errorResult("传入信息出错!");
        }
        List<DynaBean> dics = metaBeanService.buildUpdateList(dicStr, "JE_CORE_DICTIONARY");
        DynaBean inserted = null;
        for (DynaBean dic : dics) {
            commonService.buildModelCreateInfo(dic);
            metaService.insert(dic);
            inserted = dic;
        }
        List<DynaBean> dicItems = metaBeanService.buildUpdateList(strData, "JE_CORE_DICTIONARYITEM");
        for (DynaBean dicItem : dicItems) {
            commonService.buildModelCreateInfo(dicItem);
            metaService.insert(dicItem);
        }
        if (inserted != null) {
            DynaBean childRoot = metaService.selectOne("JE_CORE_DICTIONARYITEM", ConditionsWrapper.builder().eq("DICTIONARYITEM_DICTIONARY_ID", inserted.getStr("JE_CORE_DICTIONARY_ID"))
                    .eq("SY_NODETYPE", "ROOT"));
            inserted.set("DICTIONARY_ITEMROOT_ID", childRoot.getStr("JE_CORE_DICTIONARYITEM_ID"));
            inserted.set(BeanService.KEY_TABLE_CODE, "JE_CORE_DICTIONARY");
            metaService.update(inserted);
            dicInfoCache.putCache(inserted.getStr("DICTIONARY_DDCODE"), inserted);
        }
        return BaseRespResult.successResult(null, "数据字典添加成功!");
    }

    @AuthCheckPermission(value = "pc-func-JE_CORE_DICTIONARY-show")
    @RequestMapping(value = "/doRemove", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @Override
    public BaseRespResult doRemove(BaseMethodArgument param, HttpServletRequest request) {
        String ids = param.getIds();
        param.setTableCode("JE_CORE_DICTIONARY");
        if (StringUtil.isNotEmpty(ids)) {
            List<DynaBean> dics = metaService.select(ConditionsWrapper.builder().table("JE_CORE_DICTIONARY")
                    .in("JE_CORE_DICTIONARY_ID", Arrays.asList(ids.split(ArrayUtils.SPLIT))));
            for (DynaBean dic : dics) {
                dicInfoCache.removeCache(dic.getStr("DICTIONARY_DDCODE"));
                //记录被删除的数据
                metaDictionaryExtService.addLog(dic.getStr("DICTIONARY_DDCODE"));
                logger.info(SecurityUserHolder.getCurrentAccountName() + ": delete dic[DdController.doRemove] - [" + dic.getStr("DICTIONARY_DDCODE") + "]");
                metaDevelopLogService.doDevelopLog("DELETE", "删除", "DIC", "数据字典", dic.getStr("DICTIONARY_DDNAME"), dic.getStr("DICTIONARY_DDCODE"), dic.getStr("JE_CORE_DICTIONARY_ID"),dic.getStr("SY_PRODUCT_ID"));
            }
        }
        return super.doRemove(param, request);
    }

    /**
     * 通过DDCode和ItemCode获取字典项列表
     * 2012-1-16 下午06:02:38
     * 此方法只针对列表字典或树形字典
     *
     * @param param
     */
    @RequestMapping(value = "/getDicItemByCode", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public JSONArray getDicItemByCode(BaseMethodArgument param, HttpServletRequest request) {
        //查询条件
        Query query = param.buildQuery();
        //字典编码
        String ddCode = getStringParameter(request, "DICTIONARY_DDCODE");
        //国际化
        boolean en = false;
        Cookie jeLang = org.springframework.web.util.WebUtils.getCookie(request, "je-local-lang");
        if (jeLang != null) {
            if ("en".equals(jeLang.getValue())) {
                en = true;
            }
        }

        //缓存key
        String cacheKey = ddCode;
        //国际化缓存key
        if (en) {
            cacheKey += "_EN";
        }

        //获取缓存数据
        String ddValueStr;
        if (Strings.isNullOrEmpty(SecurityUserHolder.getCurrentAccountTenantId())) {
            ddValueStr = dicCache.getCacheValue(cacheKey);
        } else {
            ddValueStr = dicCache.getCacheValue(SecurityUserHolder.getCurrentAccountTenantId(), cacheKey);
        }

        //缓存为空 或者 有where条件
        if (StringUtil.isEmpty(ddValueStr) || !query.getCustom().isEmpty()) {
            //获取数据字典信息缓存
            DynaBean dictionary = dicInfoCache.getCacheValue(ddCode);
            if (dictionary == null) {
                dictionary = metaService.selectOne("JE_CORE_DICTIONARY", ConditionsWrapper.builder().eq("DICTIONARY_DDCODE", ddCode).eq("DICTIONARY_DDTYPE", DDType.LIST).apply("and (SY_STATUS = '' or SY_STATUS = '1')"));
            }

            //获取字典项数据
            if (dictionary == null) {
                logger.error("数据字典【" + ddCode + "】未找到!");
                ddValueStr = "[]";
            } else {
                //查询字典项数据
                List<DictionaryItemVo> itemVoList = dictionaryRpcService.buildChildrenList(dictionary, en, query, "");
                ddValueStr = JSON.toJSONString(itemVoList);
                //查询条件为空时加入缓存
                if (query.getCustom().isEmpty()) {
                    if (Strings.isNullOrEmpty(SecurityUserHolder.getCurrentAccountTenantId())) {
                        dicCache.putCache(cacheKey, ddValueStr);
                    } else {
                        dicCache.putCache(SecurityUserHolder.getCurrentAccountTenantId(), cacheKey, ddValueStr);
                    }
                }
            }
        }

        return DirectJsonResult.buildArrayResult(ddValueStr);
    }

    /**
     * 根据字典列表，获取字典项，此方法也只适用于列表字典和树形字典
     *
     * @param param
     * @param request
     * @return
     */
    @RequestMapping(value = "/getDicItemByCodes", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public JSONObject getDicItemByCodes(BaseMethodArgument param, HttpServletRequest request) {
        String ddListCodes = getStringParameter(request, "ddListCodes");
        JSONObject ddValues = new JSONObject();
        Boolean en = false;
        Cookie jeLang = org.springframework.web.util.WebUtils.getCookie(request, "je-local-lang");
        if (jeLang != null) {
            if ("en".equals(jeLang.getValue())) {
                en = true;
            }
        }

        String currentTenantId = SecurityUserHolder.getCurrentAccountTenantId();
        String ddValueStr;
        for (String ddCode : ddListCodes.split(",")) {
            if (Strings.isNullOrEmpty(currentTenantId)) {
                ddValueStr = dicCache.getCacheValue(ddCode + (en ? "_EN" : ""));
            } else {
                ddValueStr = dicCache.getCacheValue(currentTenantId, ddCode + (en ? "_EN" : ""));
            }

            if (StringUtil.isEmpty(ddValueStr)) {
                DynaBean dictionary = dicInfoCache.getCacheValue(ddCode);
                if (dictionary == null) {
                    dictionary = metaService.selectOne("JE_CORE_DICTIONARY", ConditionsWrapper.builder().eq("DICTIONARY_DDCODE", ddCode).apply("and (SY_STATUS = '' or SY_STATUS = '1')"));
                }
                if (dictionary == null) {
                    logger.error("数据字典【" + ddCode + "】未找到，你查看字典数据!");
                    ddValueStr = "[]";
                    continue;
                }
                List<DictionaryItemVo> itemVoList = dictionaryRpcService.buildChildrenList(dictionary, en, new Query(), "");
                ddValueStr = JSON.toJSONString(itemVoList);
                if (Strings.isNullOrEmpty(currentTenantId)) {
                    dicCache.putCache(ddCode + (en ? "_EN" : ""), ddValueStr);
                } else {
                    dicCache.putCache(currentTenantId, ddCode + (en ? "_EN" : ""), ddValueStr);
                }
            }
            ddValues.put(ddCode + (en ? "_EN" : ""), JSONArray.parseArray(ddValueStr));
        }

        return ddValues;
    }

    @RequestMapping(value = "/getDicByCode", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult getDicByCode(BaseMethodArgument param, HttpServletRequest request) {
        String ddCode = getStringParameter(request, "ddCode");
        DynaBean dictionary = metaService.selectOne("JE_CORE_DICTIONARY", ConditionsWrapper.builder().eq("DICTIONARY_DDCODE", ddCode).apply("and (SY_STATUS = '' or SY_STATUS = '1')"));
        return BaseRespResult.successResult(dictionary);
    }

    /**
     * 获取所有列表字典项，也只适用于列表字典和树形字典
     */
    @RequestMapping(value = "/getAllListDicItem", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult getAllListDicItem(BaseMethodArgument param) {
        JSONObject returnObj = dictionaryRpcService.getAllListDicItem();
        return BaseRespResult.successResult(returnObj);
    }

    /**
     * 清空字典缓存
     * @param param
     */
    @RequestMapping(value = "/clearCache", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult clearCache(BaseMethodArgument param, HttpServletRequest request) {
        String ddCode = getStringParameter(request, "ddCode");
        String currentTenantId = SecurityUserHolder.getCurrentAccountTenantId();
        if (StringUtil.isNotEmpty(ddCode)) {
            for (String dc : ddCode.split(",")) {
                dicCache.removeCache(dc);
                dicInfoCache.removeCache(dc);
                dicQuickCache.removeCache(dc);
                dicCache.removeCache(currentTenantId,dc);
            }
        } else {
            dicCache.clear();
            dicInfoCache.clear();
            dicQuickCache.clear();
        }
        return BaseRespResult.successResult(null, "清除成功!");
    }

    /**
     * 僵尸字典，没有被功能表单使用的字典
     */
    @AuthCheckPermission(value = "pc-func-JE_CORE_DICTIONARY-show")
    @RequestMapping(value = "/notUseDictionary", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult notUseDictionary(BaseMethodArgument param) {
        return BaseRespResult.successResult(metaDictionaryExtService.selectNotUseDictionary());
    }

    /**
     * 丢失字典，功能表单中配置了，但是在字典功能中没有
     */
    @AuthCheckPermission(value = "pc-func-JE_CORE_DICTIONARY-show")
    @RequestMapping(value = "/notFindDictionary", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult notFindDictionary(BaseMethodArgument param) {
        return BaseRespResult.successResult(metaDictionaryExtService.selectNotFindDictionary("",null));
    }

    /**
     * 生成字典摘要信息
     */
    @AuthCheckPermission(value = "pc-func-JE_CORE_DICTIONARY-show")
    @RequestMapping(value = "/resume", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult dictionaryResume(BaseMethodArgument param, HttpServletRequest request) {
        String ids = getStringParameter(request, "ids");
        String[] idArr = ids.split(",");
        String resumeStr = metaDictionaryExtService.generateDictionaryResumeToMeta(idArr);
        return BaseRespResult.successResult(resumeStr, "生成成功");
    }

    @AuthCheckPermission(value = "pc-func-JE_CORE_DICTIONARY-show")
    @RequestMapping(value = "/doSave", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @Override
    public BaseRespResult doSave(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        //检查编码有没有重复
        String DdCode = dynaBean.getStr("DICTIONARY_DDCODE");
        List<DynaBean> select = metaService.select("JE_CORE_DICTIONARY", ConditionsWrapper.builder().eq("DICTIONARY_DDCODE", DdCode));
        if (select == null || select.size() > 0){
            return BaseRespResult.errorResult("数据编码重复，请重新输入编码！");
        }
        //构建字典基础信息
        //buildDdInfo(dynaBean);
        //构建创新基础信息
        commonService.buildModelCreateInfo(dynaBean);
        //构建编号
        if (StringUtil.isNotEmpty(param.getCodeGenFieldInfo())) {
            commonService.buildCode(param.getCodeGenFieldInfo(), dynaBean);
        }
        //保存数据
        DynaBean inserted = commonService.doSave(dynaBean);
        //在子表中增加root节点
        metaService.insert(buildDdItemInfo(inserted));
        //检测子功能是否增加ROOT节点 (子功能多树)//todo
        commonService.doChildrenTree(inserted, param.getFuncCode());
        //把字典项的根节点ID 存放到字典表中并缓存
        /*inserted.set("DICTIONARY_ITEMROOT_ID", item.getStr("JE_CORE_DICTIONARYITEM_ID"));
        inserted.set(BeanService.KEY_TABLE_CODE, "JE_CORE_DICTIONARY");
        metaService.update(inserted);*/
        dicInfoCache.putCache(inserted.getStr("DICTIONARY_DDCODE"), inserted);
        metaDevelopLogService.doDevelopLog("CREATE", "创建", "DIC", "数据字典", inserted.getStr("DICTIONARY_DDNAME"), inserted.getStr("DICTIONARY_DDCODE"), inserted.getStr("JE_CORE_DICTIONARY_ID"),inserted.getStr("SY_PRODUCT_ID"));
        //返回给前台
        return BaseRespResult.successResult(inserted);
    }

    private DynaBean buildDdItemInfo(DynaBean inserted) {
        String id = JEUUID.uuid();
        DynaBean dynaBean = new DynaBean("JE_CORE_DICTIONARYITEM", false);
        dynaBean.setStr("JE_CORE_DICTIONARYITEM_ID", id);
        dynaBean.setStr("SY_FLAG", "1");
        dynaBean.setStr("SY_ORDERINDEX", "0");
        dynaBean.setStr("SY_NODETYPE", "ROOT");
        dynaBean.setStr("SY_LAYER", "0");
        dynaBean.setStr("DICTIONARYITEM_DICTIONARY_ID", inserted.getStr("JE_CORE_DICTIONARY_ID"));
        dynaBean.setStr("SY_TREEORDERINDEX", "000001");
        dynaBean.setStr("SY_PATH", "/" + id);
        commonService.buildModelCreateInfo(dynaBean);
        return dynaBean;
    }

    private void buildDdInfo(DynaBean dynaBean) {
        dynaBean.set("DICTIONARY_CLASS", "");
        dynaBean.set("DICTIONARY_METHOD", "");
        dynaBean.set("DICTIONARY_CLASSNAME", "");
        dynaBean.set("DICTIONARY_SQL", "");
        dynaBean.set("DICTIONARY_WHERESQL", "");
        dynaBean.set("DICTIONARY_ORDERSQL", "");
        dynaBean.set("DICTIONARY_FIELDCONFIGS", "");
        dynaBean.set("DICTIONARY_DICTYPE", "");
        dynaBean.set("JE_CORE_DICTIONARY_ID", "");
        dynaBean.set("SY_MODIFYTIME", "");
        dynaBean.set("SY_PDID", "");
        dynaBean.set("SY_PYJZ", "");
        dynaBean.set("SY_FLAG", "");
        dynaBean.set("SY_MODIFYORGNAME", "");
        dynaBean.set("SY_MODIFYORGID", "");
        dynaBean.set("SY_PYQC", "");
        dynaBean.set("SY_FORMUPLOADFILES", "");
        dynaBean.set("SY_ORDERINDEX", "0");
        dynaBean.set("SY_CREATETIME", new Date());
        dynaBean.set("SY_MODIFYUSERNAME", "");
        dynaBean.set("SY_MODIFYUSERID", "");
        dynaBean.set("SY_AUDFLAG", "");
        dynaBean.set("SY_STATUS", "");
        dynaBean.set("SY_JECORE", "0");
        dynaBean.set("SY_JESYS", "1");
        dynaBean.set("DICTIONARY_ITEMROOT_ID", "");
        dynaBean.set("DICTIONARY_ZDXGY", "");
    }

    @AuthCheckPermission(value = "pc-func-JE_CORE_DICTIONARY-show")
    @RequestMapping(value = "/doUpdate", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @Override
    public BaseRespResult doUpdate(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        //检查编码有没有重复
        String DdCode = dynaBean.getStr("DICTIONARY_DDCODE");
        List<DynaBean> select = metaService.select("JE_CORE_DICTIONARY", ConditionsWrapper.builder()
                .ne("JE_CORE_DICTIONARY_ID",dynaBean.getPkValue())
                .eq("DICTIONARY_DDCODE", DdCode));
        if (select == null || select.size() > 0){
            return BaseRespResult.errorResult("数据编码重复，请重新输入编码！");
        }
        //清空原字典缓存
        DynaBean oldDic = metaService.selectOneByPk("JE_CORE_DICTIONARY", dynaBean.getStr("JE_CORE_DICTIONARY_ID"));
        dicInfoCache.removeCache(oldDic.getStr("DICTIONARY_DDCODE"));
        //构建修改信息
        commonService.buildModelModifyInfo(dynaBean);

        //处理单附件多附件上传
        commonService.doSaveFileMetadata(dynaBean, param.getBatchFilesFields(), param.getUploadableFields(), param.getFuncCode());

        //更新数据
        metaService.update(dynaBean);

        dicInfoCache.putCache(dynaBean.getStr("DICTIONARY_DDCODE"), dynaBean);
        metaDevelopLogService.doDevelopLog("UPDATE", "修改", "DIC", "数据字典", dynaBean.getStr("DICTIONARY_DDNAME"), dynaBean.getStr("DICTIONARY_DDCODE"), dynaBean.getStr("JE_CORE_DICTIONARY_ID"),dynaBean.getStr("SY_PRODUCT_ID"));
        //如果是操作视图，则数据重新查询
        return BaseRespResult.successResult(dynaBean);
    }

    /**
     * 放入回收站、逻辑删除
     */
    @AuthCheckPermission(value = "pc-func-JE_CORE_DICTIONARY-show")
    @RequestMapping(value = "/putRecycled", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult putRecycled(BaseMethodArgument param, HttpServletRequest request) {
        String ids = getStringParameter(request, "ids");
        String ddCode = getStringParameter(request, "ddCode");
        String[] idArr = ids.split(",");

        metaService.executeSql(ConditionsWrapper.builder().apply("update je_core_dictionary set SY_STATUS = '0', DICTIONARY_DELETETIME = '"+
                                new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss").format(new Date())+"', DICTIONARY_DELETEUSERID = '"+
                                SecurityUserHolder.getCurrentAccountRealUser().getId()+"', DICTIONARY_DELETEUSERNAME = '"+
                                SecurityUserHolder.getCurrentAccountName()+"' where JE_CORE_DICTIONARY_ID in ("+StringUtil.buildArrayToString(idArr)+")"));
        //清除字典缓存
        String currentTenantId = SecurityUserHolder.getCurrentAccountTenantId();
        if (StringUtil.isNotEmpty(ddCode)) {
            for (String dc : ddCode.split(",")) {
                dicCache.removeCache(dc);
                dicInfoCache.removeCache(dc);
                dicQuickCache.removeCache(dc);
                dicCache.removeCache(currentTenantId,dc);
            }
        } else {
            dicCache.clear();
            dicInfoCache.clear();
            dicQuickCache.clear();
        }
        return BaseRespResult.successResult("操作成功");
    }

    /**
     * 还原 返回原处
     */
    @AuthCheckPermission(value = "pc-func-JE_CORE_DICTIONARY-show")
    @RequestMapping(value = "/restore", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult restore(BaseMethodArgument param, HttpServletRequest request) {
        String ids = getStringParameter(request, "ids");
        String ddCode = getStringParameter(request, "ddCode");
        String[] idArr = ids.split(",");

        metaService.executeSql(ConditionsWrapper.builder().apply("update je_core_dictionary set SY_STATUS = '1', DICTIONARY_DELETETIME = ''," +
                " DICTIONARY_DELETEUSERNAME = '' where JE_CORE_DICTIONARY_ID in ("+StringUtil.buildArrayToString(idArr)+")"));
        //清除字典缓存
        String currentTenantId = SecurityUserHolder.getCurrentAccountTenantId();
        if (StringUtil.isNotEmpty(ddCode)) {
            for (String dc : ddCode.split(",")) {
                dicCache.removeCache(dc);
                dicInfoCache.removeCache(dc);
                dicQuickCache.removeCache(dc);
                dicCache.removeCache(currentTenantId,dc);
            }
        } else {
            dicCache.clear();
            dicInfoCache.clear();
            dicQuickCache.clear();
        }
        return BaseRespResult.successResult("操作成功");
    }

    /**
     * SQL列表、SQL树形
     * Sql美化
     * @param param
     */
    @RequestMapping(value = "/sqlBeautify", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult sqlBeautify(BaseMethodArgument param, HttpServletRequest request) {
        String sql = getStringParameter(request, "sql");
        if (Strings.isNullOrEmpty(sql)) {
            return BaseRespResult.errorResult("参数错误！");
        }
        String formatSql = "";
        try {
            formatSql = new BasicSqlFormatterUtil()
                    .format(sql);
//            formatSql = SQLUtils.formatMySql(sql);
        }catch (Exception e){
            e.printStackTrace();
        }
        //不同类型数据库
        //SQLUtils.format(sql, DbType.MYSQL.getDb());
        if (Strings.isNullOrEmpty(formatSql)){
            return BaseRespResult.errorResult("sql格式错误，请检查！");
        }
        return BaseRespResult.successResult(formatSql, "生成成功!");
    }

}
